<?php
/*
 * 潮流资讯控制器。<br/>
 * 潮流资讯控制器提供以下功能：<br/>1. 创建资讯<br/>2. 更新资讯<br/>3. 分页展示资讯<br/>4. 根据tag查找关联资讯
 * <br/>5. 按照月份分类展示资讯
 */
class InfoContentController extends CController
{
	const PAGE_SIZE=6;

	/**
	 * @var string specifies the default action to be 'list'.
	 */
	public $defaultAction='list';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	static $MONTH_COUNT = array();
	
	/**
     * 初始化静态数组$MONTH_COUNT
	 */
	public function init()
	{
		$connection = Yii::app()->db;
		$sql = 'select min(create_time) as mintime from infoContent';
		// 获得数据库中最早创建的信息的时间戳
		$min_time = $connection->createCommand($sql)->queryScalar();
		$year = date('Y',$min_time);
		$month = date('n',$min_time);
		$currentMonth = mktime(0,0,0,date('n'),1,date('Y'));
		while(true)
		{
			$time = mktime(0,0,0,$month,1,$year);
			if ($time > $currentMonth) {
				break;
			}
			$p_year = date('Y',$time);
			$p_month = date('n',$time);
			$next_month = mktime(0,0,0,$month+1,1,$year);
			
			$c_criteria = new CDbCriteria;
		    $c_criteria->condition='create_time>='.$time.' and create_time<'.$next_month;;
		    $count = infoContent::model()->count($c_criteria);
		    
			self::$MONTH_COUNT[$p_year][$p_month]=$count;
			$month++;
		}
		krsort(self::$MONTH_COUNT);
	}
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'list' and 'show' actions
				'actions'=>array('list','show','ajax'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('*'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('*'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Shows a particular model.
	 */
	public function actionShow()
	{
		// 更新本月创建的资讯数量
		$c_criteria = new CDbCriteria;
		$c_criteria->condition='create_time>='.mktime(0,0,0,date('n'),1,date('Y'));
		$count = infoContent::model()->count($c_criteria);
		self::$MONTH_COUNT[date('Y')][date('n')] = $count;
		
		//找出所有热门资讯
		$h_criteria = new CDbCriteria;
		$h_criteria->condition='is_hot=1';
		$hots = infoContent::model()->findAll($h_criteria);
		
		if (isset($_GET['id'])) {
			$id = $_GET['id'];
			$nav = array();
			$nav['last'] = infoContent::model()->findbyPk($id-1);
			$nav['next'] = infoContent::model()->findbyPk($id+1);
			$infoContent = $this->loadinfoContent();
			
			// 根据id找出此id对应的所有tag，并根据这些tag找出创建时间最晚的10个关联的infoContent
			$relatedSql = "select * from infoContent where id in ".
			                "(select infoId from InfoTag where tagId in ".
			                  "(select tagId from InfoTag where infoId=$id) ".
			                "and infoId!=$id) ".
			              "order by create_time DESC limit 10;";
			
			$related = infoContent::model()->findAllBySql($relatedSql);
			$this->render('show',array('model'=>$infoContent,
		                               'hots'=>$hots,
		                               'classes'=>self::$MONTH_COUNT,
			                           'nav'=>$nav,
			                           'related'=>$related,));
			
		} else {
			throw new CHttpException(404,'Invalid request. Please do not repeat this request again.');
		}
		
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionCreate()
	{
		$model=new infoContent;
		if(isset($_POST['infoContent']))
		{
			$model->attributes=$_POST['infoContent'];
			$model->create_time = time();
			if($model->save())
				$this->redirect(array('show','id'=>$model->id));
		}
		$this->render('create',array('model'=>$model));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionUpdate()
	{
		$model=$this->loadinfoContent();
		if(isset($_POST['infoContent']))
		{
			$model->attributes=$_POST['infoContent'];
			$model->update_time = time();
			if($model->save())
				$this->redirect(array('show','id'=>$model->id));
		}
		$this->render('update',array('model'=>$model));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'list' page.
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadinfoContent()->delete();
			$this->redirect(array('list'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionList()
	{
		$criteria=new CDbCriteria;
		
		if (isset($_GET['month'])) {
			$month = $_GET['month'];
			$str = explode('-', $month);
			$start_month = mktime(0,0,0,$str[1],1,$str[0]);
			
			$next_month = mktime(0,0,0,date('n',$start_month)+1,1,date('Y',$start_month));
			$criteria->condition='create_time>='.$start_month.' and create_time<'.$next_month;
		}

		$pages=new CPagination(infoContent::model()->count($criteria));
		$pages->pageSize=self::PAGE_SIZE;
		$pages->applyLimit($criteria);

		$models=infoContent::model()->findAll($criteria);

		// 更新本月创建的资讯数量
		$c_criteria = new CDbCriteria;
		$c_criteria->condition='create_time>='.mktime(0,0,0,date('n'),1,date('Y'));
		$count = infoContent::model()->count($c_criteria);
		self::$MONTH_COUNT[date('Y')][date('n')] = $count;
		
		//找出所有热门资讯
		$h_criteria = new CDbCriteria;
		$h_criteria->condition='is_hot=1';
		$hots = infoContent::model()->findAll($h_criteria);
		$content = array(
			'models'=>$models,
			'pages'=>$pages,
		    'classes'=>self::$MONTH_COUNT,
		    'hots'=>$hots,
		);
		$this->render('list',$content);
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$this->processAdminCommand();

		$criteria=new CDbCriteria;

		$pages=new CPagination(infoContent::model()->count($criteria));
		$pages->pageSize=self::PAGE_SIZE;
		$pages->applyLimit($criteria);

		$sort=new CSort('infoContent');
		$sort->applyOrder($criteria);

		$models=infoContent::model()->findAll($criteria);

		$this->render('admin',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
		));
	}

	public function actionAjax()
	{
		if (!Yii::app()->request->isAjaxRequest)
		{
			throw new CHttpException(500,'Only ajax requests');
		}
		echo 'dsddfs';
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
	 */
	public function loadinfoContent($id=null)
	{
		if($this->_model===null)
		{
			if($id!==null || isset($_GET['id']))
				$this->_model=infoContent::model()->findbyPk($id!==null ? $id : $_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

	/**
	 * Executes any command triggered on the admin page.
	 */
	protected function processAdminCommand()
	{
		if(isset($_POST['command'], $_POST['id']) && $_POST['command']==='delete')
		{
			$this->loadinfoContent($_POST['id'])->delete();
			// reload the current page to avoid duplicated delete actions
			$this->refresh();
		}
	}
}
